package com.bdzl.admin.controller.data;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.alibaba.excel.EasyExcel;
import com.bdzl.admin.dao.data.VehBrandDao;
import com.bdzl.admin.util.excel.StudentListener;
import com.bdzl.admin.util.excel.VehBrandVOListener;
import com.bdzl.pub.controller.BaseController;
import com.bdzl.pub.enums.CountryEnum;
import com.bdzl.pub.util.file.BASE64DecodedMultipartFile;
import com.bdzl.pub.util.file.OssUploadFileUtil;
import com.bdzl.pub.vo.data.VehBrandVO;
import com.bdzl.pub.vo.data.VehModelVO;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.bdzl.pub.entity.data.VehBrandDO;
import com.bdzl.admin.service.data.VehBrandService;
import com.bdzl.pub.util.param.PageUtils;
import com.bdzl.pub.util.param.Query;
import com.bdzl.pub.util.param.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 车辆品牌表
 * 
 * @author yangyicai
 * @email yangyicai@foxmail.com
 * @date 2021-03-23 13:57:43
 */
 
@Controller
@RequestMapping("/bdzl/vehBrand")
public class VehBrandController extends BaseController {
	@Autowired
	private VehBrandService vehBrandService;
	@Autowired
	private VehBrandDao vehBrandDao;
	
	@GetMapping()
	String VehBrand(){
	    return "bdzl/vehBrand/vehBrand";
	}
	
	@ResponseBody
	@GetMapping("/list")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<VehBrandDO> vehBrandList = vehBrandService.list(query);
		int total = vehBrandService.count(query);
		PageUtils pageUtils = new PageUtils(vehBrandList, total);
		return pageUtils;
	}

	
	@GetMapping("/add")
	String add(){
	    return "bdzl/vehBrand/add";
	}

	@GetMapping("/edit/{brandId}")
	@ResponseBody
	R edit(@PathVariable("brandId") Integer brandId,Model model){
		VehBrandDO vehBrand = vehBrandService.get(brandId);
	   return R.ok(vehBrand);
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	public R save(@Validated @RequestBody  VehBrandDO vehBrand) throws IOException {
		// TODO: 2021/5/6 创建人id
		vehBrand.setBrandState(super.getUserId());
/*		MultipartFile logo = BASE64DecodedMultipartFile.base64ToMultipart(vehBrand.getBrandLogo());
		String logourl = OssUploadFileUtil.RandomFileName.uploadToOSS(logo, "mse/" +"/vehBrand");*/

		MultipartFile logo = BASE64DecodedMultipartFile.base64ToMultipart(vehBrand.getBrandLogo());
		String docUrl = OssUploadFileUtil.RandomFileName.uploadToOSS(logo, "loan/" +"contractUtils");
		vehBrand.setBrandLogo(docUrl);
		if(vehBrandService.save(vehBrand)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	public R update(@Validated @RequestBody VehBrandDO vehBrand) throws IOException{
		if (vehBrand.getBrandLogo() != null && vehBrand.getBrandLogo()!= "" && vehBrand.getBrandLogo().indexOf("https") != 0) {//图片路径,图片二进制编码不是空
			MultipartFile logo = BASE64DecodedMultipartFile.base64ToMultipart(vehBrand.getBrandLogo());
			String docUrl = OssUploadFileUtil.RandomFileName.uploadToOSS(logo, "loan/" +"contractUtils");
			vehBrand.setBrandLogo(docUrl);
		}
		vehBrandService.update(vehBrand);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@DeleteMapping( "/remove/{brandId}")
	@ResponseBody
	public R remove(  @PathVariable("brandId") Integer brandId){
		if(vehBrandService.remove(brandId)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	public R remove(@RequestParam("ids[]") Integer[] brandIds){
		vehBrandService.batchRemove(brandIds);
		return R.ok();
	}


	@ResponseBody
	@GetMapping("/vBAndUserlist")
	public PageUtils vBAndUserlist(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		int total = vehBrandService.vBAndUserlistCount(query);
		List<VehBrandVO> vehBrandList = vehBrandService.vBAndUserlist(query);
		PageUtils pageUtils = new PageUtils(vehBrandList, total);
		return pageUtils;
	}

	@GetMapping("/countryEnum")
	@ResponseBody
	public R getCountryEnum(){
		List<String> enumNames = Stream.of(CountryEnum.values()).map(Enum::name).collect(Collectors.toList());
		return  R.ok(enumNames);
	}


	// 导出
	@GetMapping("download")
	public void download(HttpServletResponse response) throws IOException {
		//获取要导出的list对象
		List<VehBrandVO> vehBrandList = vehBrandService.vBAndUserlist(null);
		// 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
		String fileName = URLEncoder.encode("测试", "UTF-8");
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		//   Student.class 是按导出类  data()应为数据库查询数据，这里只是模拟
		EasyExcel.write(response.getOutputStream(), VehBrandVO.class).sheet("模板").doWrite(vehBrandList);
	}

	/**
	 * 读取 excel
	 * @return
	 */
	@PostMapping("upload")
	@ResponseBody
	public R upload(MultipartFile file) throws IOException {
		//写法一
		// sheet里面可以传参 根据sheet下标读取或者根据名字读取 不传默认读取第一个
		EasyExcel.read(file.getInputStream(), VehBrandVO.class, new VehBrandVOListener(vehBrandDao)).sheet().doRead();
		// 写法2：
        /*ExcelReader excelReader = EasyExcel.read(file.getInputStream(), Student.class, new StudentListener(studentDao)).build();
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        excelReader.read(readSheet);
        // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
        excelReader.finish();*/
		return R.ok();
	}


}
